package com.gcb.xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;

public class XmlHandler {

	private static List<Book> list;
	private String sXml = "<books><book id='01'><name>java编程思想</name><price>$17.5</price>"
			+ "</book><book id='02'><name>java核心技术</name><price>$8.5</price>"
			+ "</book></books>";

	public XmlHandler() {
		// TODO Auto-generated constructor stub
	}

	@SuppressWarnings("unchecked")
	public void parserString(String sXml) {
		try {
			Document document = DocumentHelper.parseText(sXml);
			list = new ArrayList<Book>();
			Element root = document.getRootElement();
			List<Element> book = root.elements("book");
			for (int i = 0; i < book.size(); i++) {
				Element item = book.get(i);
				Book bk = new Book();
				bk.setId(item.attributeValue("id"));
				Element name = item.element("name");
				bk.setName(name.getText());
				Element price = item.element("price");
				bk.setPrice(price.getText());
				list.add(bk);
			}
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void createXml() {
		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("books");
		for (int i = 0; i < list.size(); i++) {
			Book bk = list.get(i);
			Element book = root.addElement("book");
			book.addAttribute("id", bk.getId());
			Element name = book.addElement("name");
			name.addText(bk.getName());
			Element price = book.addElement("price");
			price.addText(bk.getPrice());
		}
		try {
			XMLWriter writer = new XMLWriter(new FileOutputStream(
					"src/com/gcb/xml/book_bak.xml"));
			writer.write(document);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 *            void
	 * @author Cre.Gu at 2012-6-19
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		XmlHandler handler = new XmlHandler();
		handler.parserString(handler.sXml);
		handler.createXml();
	}

}
